So I’ve got a txt file where each line is a file path, I would like to:
- Read this txt file (line-by-line).
- Delete all lines that do not end with
,-,.txt - In the remaining lines, delete everything from after the last
/to the,-,.txt. - Write the output to a new txt.
How could this be done with sed?
Input:
/a/b1/
/a/b1/car
/a/b1/car/bil/
/a/b1/car/bil/,-,.txt
/a/b2/
/a/b2/flower
/a/b2/flower/bil/
/a/b2/flower/bil/,-,.txt
/a/b2/
/a/b2/boat
/a/b2/boat/baat/
/a/b2/boat/baat/abc,-,.txt
Second step:
/a/b1/car/bil/,-,.txt
/a/b2/flower/bil/,-,.txt
/a/b2/boat/baat/abc,-,.txt
Third step/desired output:
/a/b1/car/bil/
/a/b2/flower/bil/
/a/b2/boat/baat/
What it does:
It reads a line at a time from
input.txt;-ntells it not to print lines by default. For each line that matches the pattern,-,\.txt$, everything consisting of a/character followed by zero or more non-/characters, up to the end of the line, is deleted (i.e., from the last/to the end of the line); I use|as the delimiter so I don’t have to escape the/.This is a fairly straightforward rendition of your requirements.
Now that you’ve posted sample input and output, I see that you want to keep the final
/(which is inconsistent with your requirement “delete everything from the last/to the,-,.txt“). To do that:This produces your expected results given your sample input.
If I were doing this on the fly, I might use a simpler approach, combining
sedandgrep: