Bash: How to Add Quotes to Each Line in a File


Often you may want to use Bash to add quotes to each line in a file.

You can use the following syntax to do so:

awk '{ print "\""$0"\""}' teams.txt > teams_new.txt

This particular example will add double quotes around each line in the file named teams.txt and save the results to a new file named teams_new.txt.

This syntax uses the awk print command to first print double quotes (which need escaped with a slash) followed by the entire existing line ( $0 ) followed by double quotes again.

The following example shows how to use this syntax in practice.

Example: How to Add Quotes to Each Line in a File Using Bash

Suppose that we have a file named teams.txt in our current directory that contains the names of various basketball teams.

We can use the cat command to first view the contents of this file:

Now suppose that we would like to add double quotes around each line in the file.

We can use the following syntax to do so:

awk '{ print "\""$0"\""}' teams.txt > teams_new.txt

The following screenshot shows how to use this syntax in practice:

Bash add quotes around each line in file

Notice that when we use the cat command to view the contents of the new file named teams_new.txt we can see that it contains the same content as the original teams.txt file but with double quotes added around each line.

Feel free to use similar syntax to add double quotes around each line in your own file.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Count Number of Unique Lines in File
Bash: How to Count Number of Blank Lines in File
Bash: Count Number of Lines in Each File in Directory

Leave a Reply