Replace a field with values specified in another file

前端 未结 3 1650
滥情空心
滥情空心 2020-12-01 20:40

I have a file that contains the map between the words. I have to refer to that file and replace those words with the mapped ones in some files. For example, below file has t

3条回答
  •  心在旅途
    2020-12-01 21:02

    You could have sed write a sed script for you:

    The mappings:

    cat << EOF > mappings
    1.12.2.4               1
    1.12.2.7               12
    1.12.2.2               5
    1.12.2.4               4
    1.12.2.6               67
    1.12.2.12              5
    EOF
    

    Input file:

    cat << EOF > infile
    The Id of the customer is 1.12.2.12. He is from Grg. 
    The Name of the machine is ASB
    The id is 1.12.2.4. He is from Psg.
    EOF
    

    Generate a script based on the mappings (GNU sed):

    sed -r -e 's:([^ ]*) +(.*):s/\\b\1\\b/\2/g:' mappings
    

    Output:

    s/\b1.12.2.4\b/1/g
    s/\b1.12.2.7\b/12/g
    s/\b1.12.2.2\b/5/g
    s/\b1.12.2.4\b/4/g
    s/\b1.12.2.6\b/67/g
    s/\b1.12.2.12\b/5/g
    

    Evaluate with another sed (GNU sed):

    sed -r -e 's:([^ ]*) +(.*):s/\\b\1\\b/\2/g:' mappings | sed -f - infile
    

    Output:

    The Id of the customer is 5. He is from Grg. 
    The Name of the machine is ASB
    The id is 1. He is from Psg.
    

    Note that the mappings are treated as regular expressions, e.g. a dot (.) can mean any character, and may need escaping either in the mappings file or when generating the sed script.

提交回复
热议问题