0

I want to trim lines less than 4 characters, except if the line begins with # or !.

Sample input:

aa
bbb
 
   
dasasdsad
! f
#
!
# s
a
&B@*!

Output:

dasasdsad
! f
#
!
# s
&B@*!

2 Answers 2

8

With grep:

< file.in grep -E '^[#!]|.{4}' > file.out

That is, select lines that either start with # or ! or contain a sequence of 4 characters.

Or with awk:

< file.in awk '/^[#!]/ || length >= 4' > file.out

Or with sed:

< file.in sed -e '/^[#!]/b' -e '/.\{4\}/!d' > file.out
0
-6

You can try something like this, code not tested:

while read line;
do
var=$(echo $line | awk '{ print length }')
if [ $var -le 4 ]; then
echo $line >> tmp.file
fi
done < your.file

This are 2 steps, while read, it writes the lines of less than 4 characters to tmp.file. With comm -23 your.file tmp.file you compare both files, suppress common lines and > you.new.file is the final saved version

5
  • 2
    You may want to read Why is using a shell loop to process text considered bad practice?. You could also run your script by shellcheck. Commented Nov 5, 2020 at 7:16
  • 1
    You seem to have syntax errors in your script, you also call awk once for each line in the file, which will be slow. Commented Nov 5, 2020 at 7:49
  • Whilst you both might be right, I wrote "You can try something like this, code not tested: " Commented Nov 6, 2020 at 8:11
  • Whilst you both may be right, it's not my intention, to write the script for the OP, but just to provide one option/direction, how it can be archived. I personally use and prefer loops, as they allow me a better reuse of existing codes and in case needed, store results as variables and obviously, I am not the only one. Commented Nov 6, 2020 at 8:20
  • 2
    I was brought here by some "low quality" flags and would recommend that you do your best to test future Answers before posting them. Stack Exchange aims to be a high-quality repository of Questions and Answers. Commented Nov 6, 2020 at 17:21

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.