Posts mit dem Label index werden angezeigt. Alle Posts anzeigen
Posts mit dem Label index 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.

Mittwoch, 13. April 2011

Shell 005: String processing

A directory contains the following

~/shell $ ls -l
00_01_boxpdb.py
00_01_realign.py
00_02_callPDB2PQR.py
00_03_getPointCharges.py
00_04_getCharge.py
01_01_connect.py


How can the leading terms be removed?


~/shell $ for i in 0*
> do
> mv $i ${i:6}
> done


The syntax is ${i:FROM:BY}. The indexing starts from 0. Also

# Is it possible to index from the right end of the string?

echo ${stringZ:-4} # abcABC123ABCabc
# Defaults to full string, as in ${parameter:-default}.
# However . . .

echo ${stringZ:(-4)} # Cabc
echo ${stringZ: -4} # Cabc
# Now, it works.
# Parentheses or added space "escape" the position parameter.