2

I have a big text file (263 lines) that contains lines something like these:

image_name.jpg: *lots of spaces* JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, baseline, precision 8, 1024x768, frames 3 \n
image_name.jpg: *lots of spaces* JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 70", progressive, precision 8, 960x540, frames 3 \n
image_name.png: *lots of spaces* PNG image data, 752 x 760, 8-bit/color RGBA, non-interlaced \n

How can I remove all the text between : and \n at once?

  • 1
    sed -e 's/:.*//' (or 's/:.*/:/' if you want to keep the :). – AlexP Dec 2 '17 at 21:14
  • is this substring *newline (\n)* occurs literally? – RomanPerekhrest Dec 2 '17 at 21:17
  • I spent a minute staring at the screen trying to decide which one of five or so text-processing tools would be "easiest" in this case... :) – ilkkachu Dec 2 '17 at 21:26
  • You have multiple : in some lines, for instance comment: "CREATOR: in second line. How that should be handled ? Is your goal to get only the stuff before the first : in line ? – Sergiy Kolodyazhnyy Dec 2 '17 at 22:18
  • 1
    @jpmc26, it probably means that those are examples, not all possible input lines, there are likely to be others. We can't really expect anyone to present the expected inputs in a formal grammar or some such. – ilkkachu Dec 4 '17 at 8:40
6

With cut:

cut -d: -f1 file

With sed:

sed -e 's/:.*//' file

With awk:

awk -F: '{print $1}' file

With GNU grep or many BSD greps (but not POSIX grep):

grep -o '^[^:]*' file

cut is the shortest one.

If you want to modify the file in-place, your sed may have an option -i that does so - but how exactly that works depends on your platform. Otherwise, > file2 && mv file2 file on the end of any of them will work.

Alternatively, with ed, in-place everywhere:

printf ',s/:.*/\nw\n' | ed file
2

ObPerl:

perl -pe 's/:.*//' file

or in-place, leaving a backup file:

perl -i.bak -pe 's/:.*//' file

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.