Posts mit dem Label sed werden angezeigt. Alle Posts anzeigen
Posts mit dem Label sed werden angezeigt. Alle Posts anzeigen

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.

Sonntag, 10. April 2011

Shell 005: Redirect Part of a File

Suppose a file contains data starting from a given keyword (the content above the keyword is considered not relevant). If only the content from after the keyword is to be redirected to a new file (in a batch), this can be done using sed.

for i in file-*.log
do
sed -n '0,/DONE/!p' $i > ${i/file/new}
done

"!" tells it to ignore everything from the start of the file "0" to the first line containing the keyword "/DONE/", then p makes it print the rest, with a shell redirection of the output to a new file.
Regards to David the H. at LinuxQuestions for pointing this out to me.