Reading line by line from a file in unix

2019-08-29 11:01发布

问题:

I am a newbie in Unix I have a file which contains a list of file names. I am trying to copy every file in the same directory but with a different extension. Its not working. Can anyone tell me why my code is bellow csl_nl.sts is the file with name of other files?

#!/bin/csh
set files = ("csl_nl.sts")
foreach file ('cat files')

  echo "Copying" $file "to" $file.cdc
  cp $file $file.cdc

end
exit 0

回答1:

this worked for me

#!/bin/csh

foreach file (`cat csl_nl.sts`)
    set a=`echo $file | awk -F"." '{print $1}'`
    echo "$a"
end


回答2:

  1. Get a Real Shell for writing scripts.
  2. Read The Bible on reading lines and file manipulation.

One example

#!/bin/sh
while IFS= read -r file; do
    printf 'Moving %s to %s\n' "$file" "${file}.cdc"
    ${file:+'false'} || cp -- "$file" "${file}.cdc"
done


回答3:

#!/bin/ksh

OLD_EXTN=old
NEW_EXTN=new

cat csl_nl.sts | while read line;
do
  if [ ! -f $line];
  then
    echo $line does not exist ;
  else
    newfn=$(dirname $line)/$(basename $line .$OLD_EXTN).$NEW_EXTN
    echo Copy from $line to $newfn
    cp $line $newfn;
  fi
done


回答4:

Can't say I'm familiar with (t)csh, but, here's the obligatory bash example:

#!/bin/bash

for file in `cat csl_ns.tst`; do
echo $file  " -> "  $file.cdc
cp $file $file.cdc
done

Depends on the formatting of the input file, but that should work if they're seperated by whitespace or lines.



回答5:

see if this helps:

#!/bin/csh
  set files = ("abc")
  foreach file (`cat $files`)
    set ext = ("cdc")
    set file2 = "$file.$ext"
    echo "Copying" $file "to" $file2;
    cp $file $file2;

  end
exit 0


标签: shell unix