I have a variable called "User": "x-73098" in multiple files and the file names like astro_root_sys-dev.txt.

How to find all the files which have "User": "x-73098" variable and replace that variable value dynamically from "User": "x-73098" to "User": "sys_user".

User value (x-73098) is not going to be the same in all files, the numbers after x- varies in many files.

  • Is that all there is on the line? Multiple per file or just one?Always that exact pattern?
    – ivanivan
    Oct 19 '18 at 2:09
  • Not multiple per file, but its just one per file. and we can use the file pattern as astro__sys-.txt
    – itgeek
    Oct 19 '18 at 2:51

This sed linear will search the documents that contain "unknown" and repalce it with "sys_user":

sed -i 's/"unknown"/"sys_user"/g' *.txt

In order to change all strings ends with -73098:

If x is a number:

sed 's/[0-9]-73098/"sys_user"/g'  *.txt

If x is small letter:

sed 's/[a-z]-73098/"sys_user"/g'  *.txt

If x is capital letter:

sed 's/[A-Z]-73098/"sys_user"/g'  *.txt

If x is capital or small letter or a number:

sed -i 's/[a-zA-Z0-9]-73098/User: "sys_user"/g' *.txt
  • I have updated the question, actually, the user value "x-73098" varies from file to file.
    – itgeek
    Oct 19 '18 at 2:46
  • Here is the script I ran, and output also mentioned below; user_value="x-74523" for FN in astro__sys-.txt; do sed -i 's/x-[a-zA-Z0-9]/"User": "$user_value"/g' $FN done output: "User": ""User": "$user_value"3098"
    – itgeek
    Oct 19 '18 at 13:55
  • @itgeek not clear to me what is your question or how I can help?
    – user88036
    Oct 19 '18 at 14:19
  • I'm exporting user value and referring that variable key name in the sed command. export user_value="x-74523"
    – itgeek
    Oct 19 '18 at 15:39
  • i ran this command to replace the value; sed -i 's/x-[a-zA-Z0-9]/"User": "$user_value"/g' astro__sys-*.txt Is this correct ?
    – itgeek
    Oct 19 '18 at 15:41


for FN in astro*.txt; do sed -r 's/(User: ")x-[[:digit:]]*"/\1sys_user"/' "$FN" > /tmp/TMP$$; mv /tmp/TMP$$ "$FN"; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.