简体   繁体   中英

Replace lines in text file inside tar file with sed and regular expressions

File b.txt in a tar file b.tar contains lines such as these:

dir1 => /dir1A
dir2 => /dir2A

I would like a concise expression for replacing it inside the tar file with a version with these lines instead:

dir1 = /dir1B
dir2 = /dir2B

The expression may rely on the fact that a copy of b.txt exists in the same directory as a.tar .

My sed skills are a bit rustly. I've tried the following but it does not quite work yet. What is my mistake? Is there an even more concise version?

tar df a.tar b.txt
echo b.txt |
  sed \#^dir1[ \t]*=>.*$#dir1 => /dir1B# |
  sed \#^dir2[ \t]*=>.*$#dir2 => /dir2B# |
  tar af a.tar -

This (is a bit less concise than I had originally hoped for but) apparently does the trick:

TMP_DIR=`mktemp -d`
cat b.txt | \
  sed 's#^\(dir1A\s*=\s*\)\(.*\)\(\s*\)$#\1/dir1B\3#' | \
  sed 's#^\(dir2A\s*=\s*\)\(.*\)\(\s*\)$#\1/dir2B\3#' > \
  $TMP_DIR/b.txt
tar fv a.tar --delete ./b.txt
tar fv a.tar -C $TMP_DIR --append ./b.txt
rm -fr $TMP_DIR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM