3

Just trying to cut any characters after the 7th on each line of a text.

I initially tried this:

sed 's/(.{7}).*/\1/' TestText.txt 

But got this response:

sed: 1: "s/(.{7}).*/\1/": \1 not defined in the RE

Then tried this:

$ sed 's/./&#/7' TestText.txt 
Ballbou#nce
Latllma#tattjsdf
dsfase,#d,
adfadfj#jen
asdfjov#moeo
$ sed -e 's/#.*//' TestText.txt 
Ballbounce
Latllmatattjsdf
dsfase,d,
adfadfjjen
asdfjovmoeo

But all it did was remove the #. I just want to remove any character after the 7th character.

8

Use sed with -r:

sed -r 's/(.{7}).*/\1/' file

Or escape the brackets:

sed 's/\(.\{7\}\).*/\1/' file

Alternatively, you can also use grep (-E activates extended regular expressions, -o prints only the matching pattern):

grep -oE '^.{7}' file

With awk:

awk '{print substr($0,1,7)}' file

And of course cut is just made for this kind of job:

cut -c1-7 file
  • 1
    You should use -E instead of -r. -E is supported by GNU and some BSDs and is going to be in the next POSIX spec. (and -r doesn't make sense) – Stéphane Chazelas Dec 15 '15 at 13:39
  • 1
    Note that on GNU systems, cut -c doesn't support multi-byte characters, using sed is a work around. – Stéphane Chazelas Dec 15 '15 at 13:42
  • 1
    grep -oE '^.{7}' (a GNUism) will remove the lines that have fewer than 7 characters. – Stéphane Chazelas Dec 15 '15 at 13:43
  • I used the cut method and that worked. Cheers! – Phil Dec 15 '15 at 13:47
  • 1
    @StéphaneChazelas Regarding -E and -r are you talking about sed ? – 123 Dec 15 '15 at 14:32

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.