4

input.txt

1,Ram,Fail
2,John,Fail
3,Ron,Success

param.txt (New Input)

1,Sam,Success
2,John,Sucess

Now i want to replace the whole line in input.txt with those present in param.txt . 1st column will act like a primary key.

Output.txt

1,Sam,Success
2,John,Sucess
3,Ron,Success

I tried as

awk 'FNR==NR{a[$1]=$2 FS $3;next}{ print $0, a[$1]}' input.txt param.txt > Output.txt 

But it is merging the file contents.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
Debaditya
  • 2,419
  • 1
  • 27
  • 46

5 Answers5

4

This might work for you (GNU sed):

 sed 's|^\([^,]*,\).*|/^\1/c\\&|' param.txt | sed -f - input.txt

Explanation:

  • Convert param.txt into a sed script using the first field as an address to change the line in the input.txt. s|^\([^,]*,\).*|/^\1/c\\&|
  • Run the script against the input.txt. sed -f - input.txt
potong
  • 55,640
  • 6
  • 51
  • 83
4

This can be done with one call to sort:

sort -t, -k1,1n -us param.txt input.txt

Use a stable numerical sort on the first comma-delimited field, and list param.txt before input.txt so that the correct, newer, lines are preferred when eliminating duplicates.

chepner
  • 497,756
  • 71
  • 530
  • 681
2

You could use join(1) to make this work:

$ join -t, -a1 -j1 Input.txt param.txt | sed -E 's/,.*?,.*?(,.*?,.*?)/\1/'
1,Sam,Success
2,John,Sucess
3,Ron,Success

sed as a pipe tail strips fields from Input.txt out of replaced lines.

This will work only if both input files are sorted by first field.

Alan
  • 504
  • 2
  • 5
2

Pure awk isn't really the right tool for the job. If you must use only awk, https://stackoverflow.com/a/5467806/1301972 is a good starting point for your efforts.

However, Unix provides some tools that will help with feeding awk the right input for what you're trying to do.

$ join -a1 -t, <(sort -n input.txt) <(sort -n param.txt) |
     awk -F, 'NF > 3 {print $1 "," $4 "," $5; next}; {print}'

Basically, you're feeding awk a single file with the lines joined on the keys from input.txt. Then awk can parse out the fields you want for proper display or for redirection to your output file.

Community
  • 1
  • 1
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
2

This should work in awk

awk -F"," 'NR==FNR{a[$1]=$0;next} ($1 in a){ print a[$1]; next}1' param.txt input.txt

Test:

$ cat input.txt 
1,Ram,Fail
2,John,Fail
3,Ron,Success
$ cat param.txt 
1,Sam,Success
2,John,Sucess
$ awk -F"," 'NR==FNR{a[$1]=$0;next} ($1 in a){ print a[$1]; next}1' param.txt input.txt 
1,Sam,Success
2,John,Sucess
3,Ron,Success
jaypal singh
  • 74,723
  • 23
  • 102
  • 147