Jahid
Jahid

Reputation: 22428

Replacing string with line number in a file

I am replacing all exit code with the line number of a bash script.

Sample file:

echo something
if conditional;then exit 1;fi
echo something else
if conditional;then exit 2;fi

Sample output:

echo something
if conditional;then exit 2;fi
echo something else
if conditional;then exit 4;fi

Currently I am doing this:

cat -n file |sed "s/\([[:blank:]]*[0-9]\+\)\(.*\)\(exit[[:blank:]]*\)\([0-9]\+\)\(.*\)/\1\2\3\1\5/" | sed "s/[[:blank:]]*[0-9]\+[[:blank:]]//"

Which does the job but it seems too complex for a simple task.

Any suggestions how I can do this efficiently?

Upvotes: 1

Views: 138

Answers (2)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

cat -n file | sed -r 's/^(\s*(\S*).*exit\s)[0-9]+/\1\2/;s/^\s*\S*\t//'

or using a couple of applications of sed rather than cat -n and sed:

sed '/exit\s[0-9]/=' file | sed -r 'N;s/^(\S+)\n(.*exit\s)[0-9]*/\2\1/;P;D'

Upvotes: 0

anubhava
anubhava

Reputation: 784938

You can use this much simpler awk command:

awk '{sub(/\<exit[[:blank:]]+[0-9]+/, "exit " NR)} 1' file
echo something
if conditional;then exit 2;fi
echo something else
if conditional;then exit 4;fi
  • NR represents current record # or line #
  • \<exit [0-9]+ is used to match exit <digits> where \< is for word boundary

Upvotes: 6

Related Questions