-1

I am a beginner at Linux and I'm trying to do a project which takes every line from a file.txt and replaces the third word with the first of each line. Here is my Shell code but it doesn't seem to work. It keeps replacing the third word with $field1 and not what's in it.

#!/bin/bash

while IFS=: read -r field1;do    
    sed -e 's/[^:]*[^:]/$field1/3'
done < file.txt
Inian
  • 80,270
  • 14
  • 142
  • 161
TdFn
  • 3
  • 1
  • 3
    you might want to change the title of your question to something more relevant, like "using variable with sed not working" and in which case you might find this answer: http://stackoverflow.com/questions/19151954/how-to-use-variables-in-a-command-in-sed – Matthias Apr 05 '17 at 10:38
  • Your `sed` command consumes the rest of `file.txt` because you are not specifying an input file. Use either a `while read` loop or `sed` (preferably the latter in most cases) but not both, unless they need to operate on separate streams or files. – tripleee Apr 05 '17 at 10:50
  • thanks for the heads up! – TdFn Apr 05 '17 at 10:52
  • You want to swap 3th and 1th or not, just 1th with 3th? – Shakiba Moshiri Apr 05 '17 at 11:29

2 Answers2

0

Make note of the single quotation marks. Place them around the field1 variable and so:

sed -e 's/[^:]*[^:]/'$field1'/3'
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319
  • Nope. I don't know why but it only duplicates the fields. Not even replacing anything. – TdFn Apr 05 '17 at 10:44
0

Try this, this will replace in the same file:

#!/bin/sh

while read -r line
do
        first=`echo $line | awk -F':' '{ print $1 }'`
        last=`echo $line | awk -F':' '{ print $3 }'`

        echo $line | sed "s/$last/$first/"

done < file.txt

Input file :

ashish:is:good
navin:is:good
how:are:you

Output :

ashish:is:ashish
navin:is:navin
how:are:how
Ashish K
  • 905
  • 10
  • 27
  • It doesn't help if I do that. I have to replace the third word with the first of each line. That bit will only print the fields. – TdFn Apr 05 '17 at 10:46
  • replace, not exchange? correct? – Ashish K Apr 05 '17 at 10:48
  • ok, that works. but ultimately i have to replace those words in the file. not just print them on screen. – TdFn Apr 05 '17 at 10:50
  • Your quoting is exactly wrong. The colons are not shell metacharacters and thus do not require quoting, while the variables could contain shell metacharacters, irregular whitespace, etc and thus *need* to be quoted. (As an experiment, use input where one of the fields is an asterisk and nothing else to see the point proven.) – tripleee Apr 05 '17 at 10:52
  • Quoting is not wrong but shouldn't have been used. Anyway thanks for mentioning. – Ashish K Apr 05 '17 at 10:56
  • @TdFn please check now. Tell me if you are still facing any issue. – Ashish K Apr 05 '17 at 11:20
  • @AshishK Great! It's perfect. Thank you very much! – TdFn Apr 05 '17 at 11:37