How to remove newline character if it is the only character in the entire file.?

I have a file which comes every day and the file data look's as below.

Vi abc.txt
a|b|c|d\n
a|g|h|j\n

Some times we receive the file with only a new line character in the file like

vi abc.txt
\n

We need to handle the shell script such a way that if the entire file contains only a new line character then remove the new line character else don't touch the file .

Do you mean a literal newline character, or the two characters

\n

?

If the former, try:

awk NF oldfile > new file

--
How big are the files?

1 Like
#!/bin/bash
file="file.log"
if ! grep -q "[[:print:]]" $file; then
        >$file
fi
1 Like

The fie size is 1byte .

Provided your system (which you fail to mention, btw) has the stat command available, try

[ $(stat -c%s "$file") = 1 ] && >"$file"
1 Like

Thanks for the response . This works for me can you explain me how it actually works.

Check if the file contains printable characters
grep -q "[[:print:]]" $file;
if not if ! truncated to zero >$file
I apologize for the not quite detailed answer, I just learn English

Even if your system doesn't have the stat command, you could also use:

[ $(wc -c < "$file") -eq 1 ] && > "$file"

The command:

wc -c < "$file"

prints the number of bytes found on its standard input (in this case the contents of the file you're interested in) and if that is equal to 1, the redirection recreates the file as an empty file.

In contrast to wc, grep with -l or -q option stops reading the input when a match has occurred.
In this case a

grep -q . file

(stop if any character is met) seems sufficient.
Because grep returns an exit status it becomes quite simple:

file=myfile.log
grep -q . "$file" || >"$file"

Note that -q is not portable. If this is an issue, use the -l option and suppress output.

file=myfile.log
grep -l . "$file" >/dev/null || >"$file"
3 Likes