Montag, 30. Mai 2011

Shell 006: Replacing String with incrementing index

Lets say we have some text as below.

header
foo
foo
foo
header
bar
bar
bar
header
baz
baz
baz

where we want the "header" be replaced by "model {1,2,3}".
I was pointed out to a couple of solutions over at LinuxQuestions.org

An awk solution.

$ awk 'BEGIN { cntr = 0 } /header/ { cntr++ ; print "model", cntr } !/header/ { print $0 }' infile

where 'infile' contains the data.

A bash solution.

#!/bin/bash

filename=data

index=1

for entry in `grep -n model $filename`
do
line=`echo $entry | awk -F":" '{print$1}'`

sed -e "$line s/model/model $index/" -i $filename

index=$(($index + 1))
done


An even shorter awk solution.

awk '$0 = /header/?"model "++c:$0' file


A one line bash solution

unset count; while read line; do [[ $line =~ header ]] && line="model $((++count))"; echo "$line" >> oufile; done < infile


Great to have the support from the online community.

Keine Kommentare:

Kommentar veröffentlichen