Reputation: 715
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
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
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