Someone_1313
Someone_1313

Reputation: 432

Add multiple elements to the text file in a specific way using Bash

I have a text file that contains a list of "word sequences" and I need to add some "" and "," to each word sequence, I´m thinking in use a bash command. Here is the data:

NTSS
NGTG
NVSQ
NITL
NFTS
...

I need to add "" to each word sequence and separate with "," Here an expected output:

"NTSS",
"NGTG",
"NVSQ",
"NITL",
...

Any recommendation with BASH to do that?

Upvotes: 0

Views: 30

Answers (1)

swingbit
swingbit

Reputation: 2745

This can be done in many ways, but sed is perfect for the job.

sed 's/^.*$/"\0",/' < file.txt

This replacement simply matches the whole line and replaces it according to what you need.

The one above is a regular expression replacement, which has the structure:

s/<pattern to match>/<replacement>/
  • ^ matches the beginning of the line
  • .* matches any character any number of times
  • $ matches the end of the line
  • In the replacement part, \0 represents the whole string that has matched the pattern (the entire line in this case)

Check out some regular expression tutorial for more.

If you prefer a purely bash alternative, you can use:

while read -r line; do echo "\"${line}\","; done < file.txt

Upvotes: 1

Related Questions