2

I need to remove the first two characters of every line in a file ( always the same ) and the last "/" if it is present.

Input is, in the file F1 :

^./inst/oracle/
^./tmp/
^./inst/maj/
^./mkcd
^./var/adm/ras/livedump/

Using :

cat F1 | sed 's#^\^\.\(.*\)/$#\1#'

I get the following result :

/inst/oracle
/tmp
/inst/maj
^./mkcd
^./var/adm/ras/livedump/

Same result with a "g" at the end of the sed

The last lines are ignored. I can't figure out why it is doing the job for the first 3 lines and then stopping.

2
  • It's obvious why your command isn't working on the fourth line — your substitute command looks for ^. at the beginning of the line and / at the end, and does nothing if it doesn't find both.  The fourth input line doesn't end with /, and so it isn't changed.  My best guess is that the same is true for the fifth line, although less obviously.  Please check your file to see whether there are any character(s) (e.g., spaces, tabs, and/or carriage returns) after the / on the fifth line. Commented Jan 9, 2016 at 4:39
  • Replace / by /*. Because / is optional.
    – Cyrus
    Commented Jan 9, 2016 at 4:39

3 Answers 3

1

Try this:

sed 's/\^\.//;s|/$||' file

Output:

/inst/oracle
/tmp
/inst/maj
/mkcd
/var/adm/ras/livedump
6
  • 1
    I would prefer s/^..// Commented Jan 9, 2016 at 3:35
  • @Cyrrus thanks but I don't get your results. I'm on AIX. Can that cause issues? Commented Jan 9, 2016 at 4:22
  • @Cyrrus I almost get your result except for the last line. The "/" remains on only the last line. All the rest is OK. Commented Jan 9, 2016 at 4:29
  • @Cyrrus I check the input file and there was a space at the end of the last line. That is why it didn't work. I can I account for that possibility? Why did my sed not work? Commented Jan 9, 2016 at 4:34
  • Try this with an optional space: sed 's/\^\.//;s|/ *$||' file
    – Cyrus
    Commented Jan 9, 2016 at 4:55
0

For variety's sake, here's the solution with a multi-line script instead of sed:

while IFS='' read -r line
do
  line="${line%/}"
  echo "${line#??}"
done
0

This should work:

sed 's|\^\.\(.*[^\/]\)\/*$|\1|g' file

Output:

/inst/oracle  
/tmp  
/inst/maj  
/mkcd   
/var/adm/ras/livedump

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .