0

If you create a file test.txt with these 2 lines, then grep | cut the second line, like this:

echo "ExportFormatIdx=14
ExportFormatNames=unquoted, quoted, more, CSVmore, ExtU, Extended, HTML, XML, Details, TOC, Custom, Primary, Core, bash, removethis" > test.txt
grep ExportFormatNames test.txt | cut -f1-14 -d','

The output is:

ExportFormatNames=unquoted, quoted, more, CSVmore, ExtU, Extended, HTML, XML, Details, TOC, Custom, Primary, Core, bash

The result: starting with the 14th comma, everything is correctly removed from that line. In this case:

, removethis

Is it possible to do the same approach (replace everything following, and including, the nth comma), but as an in-place line change, using sed?

If you do:

grepresult="$(grep ExportFormatNames test.txt | cut -f1-14 -d',')"; echo "grep result is $grepresult";sed -i '/ExportFormatNames/c\"$grepresult"' test.txt

The result of

cat test.txt

is:

ExportFormatIdx=14
"$grepresult"

Will sed only accept string literals? If so, is there a workaround?

user3447273
  • 351
  • 1
  • 4
  • 12
  • You need to use double quotes in order for variable expansion to take place. – Wiktor Stribiżew Oct 21 '21 at 22:23
  • Tried it in double quotes like this: sed -i "/ExportFormatNames/c\$grepresult" test.txt, which did not work, but this one did: sed -i '/ExportFormatNames/c\'"$grepresult" test.txt - thanks! – user3447273 Oct 21 '21 at 22:31

0 Answers0