1

In my Windows 10, I have 100+ XML files under the same directory, which contain the same tag, let's say <Number>, with different content, such as <Number>4564564</Number>, or <Number>7777</Number>.

Now, I want to substitute all the different values with 123456.

I installed Git bash and find sed may be useful. But, AFAIK, for in bash cannot iterate files under a directory, and I know no other way of iterating files in bash, instead, FOR in Windows batch can(correct me if I am wrong). So,

  • can I iterate with batch FOR and in the loop, use sed of bash, i.e., mixing GNU bash commands and cmd commands? As I tested it seems impossible.
  • if the previous is impossible, can I do it or in pure bash script, or in pure batch?

What I have is a batch like this:

@echo on
setlocal ENABLEEXTENSIONS
set here=%cd%
for /R %here% %%G in (*.xml) do (
    echo %%G
    for /F "skip=2 tokens=* " %%H in (%%G) do (
        echo %%H | sed -r 's:<Number>([0-9]+)</Number>:<Number>123456</Number>:'
    )
)
endlocal

Running this batch in cmd and Git bash gives me the same error:

The system cannot find the path specified.

I have Git bash installed and apparently, sed.exe can be found both in Git bash and cmd. In cmd, sed --version gives me:

sed (GNU sed) 4.2.2
...
WesternGun
  • 11,303
  • 6
  • 88
  • 157

1 Answers1

1

This would be a pure sed solution:

sed -r 's:<Number>([0-9]+)</Number>:<Number>123456</Number>:' -i *.xml

(Note, sed can operate on multiple files, in sequence. The -i flag is instructing it to do in-place edits.)

If you need to do something else alongside, you can loop over files with this pure bash+sed script:

for file in *.xml; do
    echo "Processing file: $file"
    sed -r 's:<Number>([0-9]+)</Number>:<Number>123456</Number>:' -i "$file"
    # ...
done
randomir
  • 17,989
  • 1
  • 40
  • 55
  • Great solution, working here! Now I wonder what batch lovers would say... – WesternGun Jul 03 '17 at 06:43
  • I'm not sure for batch lovers, but PowerShell lovers would say to use [`Get-Content .. -replace`](https://stackoverflow.com/questions/17144355/how-can-i-replace-every-occurrence-of-a-string-in-a-file-with-powershell). Unix lovers would say: come over, we have (more) cookies. :) – randomir Jul 03 '17 at 14:37