Dawid
Dawid

Reputation: 715

Bash: replace empty line with string

How to replace blank line in text file, let's say that file is:

first

third

with some string( for ex. "second" ) using Bash? I wanna make sth. like this:

first
second
third

Upvotes: 3

Views: 16794

Answers (3)

Yang
Yang

Reputation: 8180

You can also use a default value for an unset or empty variable:

cat file.txt | while read line
do
   echo "${line:-second}"  # empty lines are default to 'second'
done > file.out

Upvotes: 7

Bill
Bill

Reputation: 5792

You can use [ -z "$line" ] to test if your line is empty and do whatever you want with it.

cat file.txt | while read line
do
   if [ -z "$line" ]
   then
     //$line is empty
   fi
done

EDIT -- if you want to replace the empty line with "second" -- so you will end up with file.out which is the new file with empty lines replaced with second

touch file.out
cat file.txt | while read line
do
       if [ -z "$line" ]
       then
         echo "second" >> file.out
       else
          echo $line >> file.out
       fi
 done

Upvotes: 3

Gumbo
Gumbo

Reputation: 655845

You can use sed:

sed -i -e 's/^$/second/' file

The -i option toggles the in-place replacement.

Upvotes: 9

Related Questions