moadeep
moadeep

Reputation: 4098

Simple sed substitution

I have a text file with a list of files with the structure ABC123456A or ABC123456AA. What I would like to do is check whether the files ABC123456ZZP also exists. i.e I want to substitute the letter(s) after ABC123456 with ZZP

Can I do this using sed?

Upvotes: 0

Views: 132

Answers (3)

Ed Morton
Ed Morton

Reputation: 203635

Look:

$ str="ABC123456AA"
$ echo "${str%[[:alpha:]][[:alpha:]]*}"
ABC123456

so do this:

while IFS= read -r tgt; do
    tgt="${tgt%[[:alpha:]][[:alpha:]]*}ZZP"
    [[ -f "$tgt" ]] && printf "%s exists!\n" "$tgt"
done < file

It will still fail for file names that contain newlines so let us know if you have that situation but unlike the other posted solutions it will work for file names with other than 9 key characters, file names containing spaces, commas, backslashes, globbing characters, etc., etc. and it is efficient.

Since you said now that you only need the first 9 characters of each line and you were happy with piping every line to sed, here's another solution you might like:

cut -c1-9 file |
while IFS= read -r tgt; do
    [[ -f "${tgt}ZZP" ]] && printf "%sZZP exists!\n" "$tgt"
done

It'd be MUCH more efficient and more robust than the sed solution, and similar in both contexts to the other shell solutions.

Upvotes: 0

peteches
peteches

Reputation: 3619

You could use sed as wilx suggests but I think a better option would be bash.

while read file; do
    base=${file:0:9}
    [[ -f ${base}ZZP ]] && echo "${base}ZZP exists!"
done < file

This will loop over each line in file then base is set to the first 9 characters of the line (excluding whitespace) then check to see if a file exists with ZZP on the end of base and print a message if it does.

Upvotes: 1

wilx
wilx

Reputation: 18228

Like this?

X=ABC123456 ;  echo ABC123456AA | sed -e "s,\(${X}\).*,\1ZZP,"

Upvotes: 2

Related Questions