0

I have a big text file I want to print only the first 4 and the first 5 and the first 8 characters of each line in one command line.

For example I have the lines:

123456789ab
ABCdefgih55

So the output have to be:

1234
ABCd
12345
ABCde
12345678
ABCdefgh
3
for len in 4 5 8; do
    cut -c "1-$len" file
done

This uses cut -c repeatedly to cut out the first part of each line of the file called file. The length of the cut out bit is depending on the loop variable len.

If you're strict about that "one line" criteria:

for len in 4 5 8; do cut -c "1-$len" file; done

Or, as an easy to use shell function:

cut_to_lengths () {
    file=$1; shift
    for len do
        cut -c "1-$len" "$file"
    done
}

Using it:

$ cut_to_lengths file 4 5 8 1
1234
ABCd
12345
ABCde
12345678
ABCdefgi
1
A

In comments you specify that you don't want to output lines if they are shorter the cut length.

To do this, we can change the cut command into an awk command:

awk -v len="$len" 'length >= len { print substr($0, 1, len) }'

Replace the cut -c "1-$len" with the above awk command in the code above.

  • if i have lines contain less than 4 characters so i don't want them to be appeared in the output. If i have in the input a line contains one character for example: 1 so it will be eapeated in the out put how to prevent the lines that contain less than 4 characters from being appeared? – Ahmed Feb 6 at 11:34
  • @Ahmed See update. – Kusalananda Feb 6 at 11:41
0

Your example is not well formated. I guess the whitespace should be a new line? If so the simplest way is to use cut

$ cut -c -4 input will print the first 4 character of each line. Repeat it with any number of characters you like.

  • Dear finswimmer i forgot to mention that i tried this command cut -c -4 input but i want to do this in one command line for the all the first 4 and 5 and 8 characters. – Ahmed Feb 6 at 8:16
0

try the following

for line in `cat input`; do echo ${line} | cut -c 1-4 && echo ${line} | cut -c 1-5 && echo ${line} | cut -c 1-8; done

this gives

1234
12345
12345678
ABCd
ABCde
ABCdefgi
  • The output does not seem to match the expected output. Also, if any line contains filename globbing characters or spaces, your code wouldn't handle it properly. – Kusalananda Feb 6 at 8:21
  • More info here. – Sparhawk Feb 6 at 8:31
  • @Zaid Amireh if i have lines contain less than 4 characters so i don't want them to be appeared in the output. If i have in the input a line contains one character for example: 1 so it will be eapeated in the out put how to prevent the lines that contain less than 4 characters from being appeared? – Ahmed Feb 6 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.