tlorin
tlorin

Reputation: 1150

Awk/sed replace in each line with previous string in the line

I have a file test.txt like this (but containing many more lines)

/foo/bar/how hello
/foo/bar/are hello
/foo/bar/you hello

I want to get this output:

/foo/bar/how how
/foo/bar/are are
/foo/bar/you you

I have tried this:

while read line
do
bla=$(echo $line | cut -f4 -d"/" | cut -f1 -d" ")
sed -i "s/hello/$bla/"
done <test.txt

But the output is:

sed: no input files
sed: no input files
sed: no input files

When I provide the filename (while read line; do bla=$(echo $line | cut -f4 -d"/" | cut -f1 -d" "); sed -i "s/hello/$bla/" test.txt ; done <test.txt), I get this:

/foo/bar/how how
/foo/bar/are how
/foo/bar/you how

I would like to replace on each line some constant pattern by a pattern appearing before on the same line and that changes from line to line. Any idea on how I could do that (using sed or awk)? Many thanks!

Upvotes: 1

Views: 1141

Answers (3)

SLePort
SLePort

Reputation: 15461

Try this:

$ sed 's~\(.*/\)\([^ ]*\) .*~\1\2 \2~' test.txt
/foo/bar/how how
/foo/bar/are are
/foo/bar/you you

Use the -i option to edit the file in place:

sed -i 's~\(.*/\)\([^ ]*\) .*~\1\2 \2~' test.txt

Explanation:

  • s: substitute
  • \(.*/\)\: any character up to last /
  • followed by \([^ ]*\): any non-space character followed by a space

Using backreference, the strings that matches the pattern are replaced with : first group (/foo/bar/) followed by repeated second group (the word after last / : how, are or you).

Upvotes: 1

sjsam
sjsam

Reputation: 21965

Below awk solution might help

awk  '{$2=$1;sub(/.*\//,"",$2)}1' test.txt

Ouput

/foo/bar/how how
/foo/bar/are are
/foo/bar/you you

Notes

  • By default awk fields are whitespace separated so, you have two fields ie $1 and $2.
  • First assign the first field of every record to second ie $2=$1
  • Then, in the second field, strip the the part till the last / using sub(/.*\//,"",$2).
  • 1 at the end is the simplest of awk command which prints each record.

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203655

$ sed 's~\([^/]*\) .*~\1 \1~' file
/foo/bar/how how
/foo/bar/are are
/foo/bar/you you

Upvotes: 2

Related Questions