Bash itself (in fact POSIX shell) provides all you need through parameter expansion with substring removal. All you need to do is check whether the line you read matches itself with the prefix removed. If it doesn't, you have a prefixed line, otherwise, you have a non-prefixed line. Then it is a simple matter of outputting the non-prefixed line and setting the prefix to the current line -- and repeat, e.g.
#!/bin/bash
pfx= ## prefix
## read each line
while read -r line; do
## if no prefix or line matches line with prefix removed
if [ -z "$pfx" -o "$line" = "${line#$pfx}" ]
then
printf "%s\n" "$line" ## output lile
pfx="$line" ## set prefix to line
fi
done < "$1"
(note: if there is a chance that an input file that does not contain a POSIX end-of-file, e.g. a '\n'
on the final line of the file, then you should check the contents of line as a condition of your while
, e.g. while read -r line || [ -n "$line" ]; do ...
)
Example Input File
$ cat string.txt
a/
a/b/c/
a/d/
bar/foo/
bar/foo2/
c/d/
c/d/e/
Example Use/Output
$ bash nonprefix.sh string.txt
a/
bar/foo/
bar/foo2/
c/d/