Skip to content

Instantly share code, notes, and snippets.

@jasonm23
Created May 10, 2010 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonm23/396607 to your computer and use it in GitHub Desktop.
Save jasonm23/396607 to your computer and use it in GitHub Desktop.
Column edits with sed / regexp

Ignore this - but if you are looking to do column edits, use unix cut it's made for this job.

Column edits with sed

Assuming you have a regular tabulated text file, e.g. a directory listing.

Extract columns from 15 - 29 for the entire input. ls -l | sed 's/(^.{14})(.{14})(.*)/\2/' # ^---^ ^---------^ ^--------^ ^---^ ^ # input \1= \2= \3= +---- output only \2 (c15-c29) # c1-14 c15-c29 the rest.

Remove columns 15 - 28 for the entire input. ls -l | sed 's/(^.{14})(.{13})(.*)/\1\3/'

Blank out columns from 15 - 28 for the entire input. ls -l | sed 's/(^.{14})(.{13})(.*)/\1------------\3/'

Remove all except columns 15-29 for lines 3-8. (leave the rest of the file intact.) ls -l | sed '3,8s/(^.{14})(.{14})(.*)/\2/'

If we want to do the same thing but only output the changed columns... We have to tell sed to delete the rest of the lines, the simplest way is to use !d, which will delete everything except the lines we want to keep.

ls -l | sed -e '3,8!d' -e '3,8s/\(^.\{14\}\)\(.\{14\}\)\(.*\)/\2/'

notice that when we use multiple commands, we have to tell sed, so we need to prefix each one with the -e option.

@jasonm23
Copy link
Author

and then I discovered 'cut' :)

So ignore this and read man cut

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment