User Tools

Site Tools


bash:files:read_a_file:troubleshooting:files_lack_their_final_newlines

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

bash:files:read_a_file:troubleshooting:files_lack_their_final_newlines [2021/01/26 14:14] – created peterbash:files:read_a_file:troubleshooting:files_lack_their_final_newlines [2021/01/26 14:17] (current) peter
Line 1: Line 1:
 ====== BASH - Files - Read a file - Troubleshooting - Files lack their final newlines ====== ====== BASH - Files - Read a file - Troubleshooting - Files lack their final newlines ======
 +
 +===== My text files are broken!  They lack their final newlines! =====
 +
 +If there are some characters after the last line in the file (or to put it differently, if the last line is not terminated by a newline character), then **read** will read it but return false, leaving the broken partial line in the read variable(s).
 +
 +You can process this after the loop:
 +
 +<code bash>
 +# Emulate cat.
 +while IFS= read -r line; do
 +  printf '%s\n' "$line"
 +done < "$file"
 +[[ -n $line ]] && printf %s "$line"
 +</code>
 +
 +or:
 +
 +<code bash>
 +# This does not work:
 +printf 'line 1\ntruncated line 2' | while read -r line; do echo $line; done
 +
 +# This does not work either:
 +printf 'line 1\ntruncated line 2' | while read -r line; do echo "$line"; done; [[ $line ]] && echo -n "$line"
 +
 +# This works:
 +printf 'line 1\ntruncated line 2' | { while read -r line; do echo "$line"; done; [[ $line ]] && echo "$line"; }
 +</code>
 +
 +<WRAP info>
 +**NOTE:**  
 +
 +The first example, beyond missing the after-loop test, is also missing quotes.
 +
 +</WRAP>
 +
 +
 +
 +----
 +
 +Alternatively, you can simply add a logical OR to the while test:
 +
 +<code bash>
 +while IFS= read -r line || [[ -n $line ]]; do
 +  printf '%s\n' "$line"
 +done < "$file"
 +
 +printf 'line 1\ntruncated line 2' | while read -r line || [[ -n $line ]]; do echo "$line"; done
 +</code>
 +
 +----
  
bash/files/read_a_file/troubleshooting/files_lack_their_final_newlines.1611670466.txt.gz · Last modified: 2021/01/26 14:14 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki