0

I'm new to unix and I'm having a hard time doing this loop.

I have a directory with a list of files and I'm able to list all of those files in a text file.

I have a text file that contains the following contents:

  • FileName01.xml
  • FileName02.xml
  • FileName03.xml
  • FileNameNN.xml

I want to create a text file separately for each of those contents. The output should be like this:

-File name of the text file: Filename01.txt -Content of the text file: FileName01.xml

And so on and so forth

I'm trying using for loop to create a text file for each of those contents and I can't seem to make it.

This is the current script that I'm working on:

#!/bin/bash
ls /directory/input > filelist.txt
for f in filelist.txt;
do
    printf f > 'file_*.txt'
done
2
  • for f in $(ls /directory/input);do echo $f > ${f}.txt; done Is this the answer you need? I use a translation software, can understand the wrong question Dec 4, 2022 at 16:23
  • @山河以无恙 please don't use $(ls): See unix.stackexchange.com/questions/128985/… ; also, even if it worked reliably, it would be less useful than for f in /directory/input/* ; …, which is nicer.. Dec 4, 2022 at 21:10

1 Answer 1

2

I suggest

#!/bin/bash

shopt -s nullglob

for f in /directory/input/*.xml; do
  bn=${f##*/}
  printf '%s\n' "$bn" > "${f%.xml}.txt"
done

See Shell Parameter Expansion for an explanation of the prefix and suffix removal syntax.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .