Replace directory line ".." using sed

How can I do this in sed?

#input                 #output
file.txt              "nothing" 
dir1/                 ../
dir1/file.txt         ../
dir1/dir2/            ../../
dir1/dir2/file.txt    ../../

      

Suppose #input is put in $ var1

sed "do something" <<< $var1
echo $var1

      

+3


source to share


2 answers


You can try this GNU sed



sed "s#dir[0-9]\+/*#\.\./#g; s#file\.txt##g"  

      

+1


source


Does the dir1 / dir2 test run correctly (no forward slash)? How does sed know if dir2 is a file or a directory? Otherwise, you can use:



echo "dir1/dir2/file.txt" | sed s#[^/]*/#../#g | sed 's#[^/]*$##'

      

0


source







All Articles