Script to read files in a directory

Dear Experts,
I am new to UNIX and I have a requirement to read the names of a file in a directory. I have some script below and in this test case I am reading the names of the files in the present directory into a variable and then looping through each file name and displaying the name back to the screen. The problem I have is although there are 5 files in the directory, it only ever displays the name of the first file and then stops. Can you assist?
Many thanks,
Mark
#!/bin/csh
set files = `ls`
foreach file ( $files )
echo 'File name:' $file
end

The script is correct.
You may have odd results if you have an alias like "alias ls='/bin/ls $LS_OPTIONS'"
and if you have "hidden" files starting whith a single .
An example:
obelix:~ # ls
. .bash_history .gconf .history .rnd tnt
.. .dmrc .gconfd .kbd .skel
.DCOPserver_obelix_:0 .exrc .gnome .kde .viminfo
.DCOPserver_obelix__0 .fonts .gnome2 .mcop .xsession-errors
.ICEauthority .fonts.cache-1 .gnome2_private .mozilla Desktop
.Xauthority .fvwm .gnupg .qt bin
obelix:~ # \ls
Desktop bin tnt
obelix:~ #
--------------------------

Similar Messages

  • PI sender communication channel not reading files from NFS directory

    Hello,
    I have a sender communication channel configured to read file from NFS directory which is on ECC server. A program in ECC generates the file and puts it on the ECC server in the output directory. PI sender communication channel is supposed to pickup this file and process it. If I give the NFS path as the source directory, I am getting error: Configured source directory '//Server/DIR/OUT' does not exist. I tried putting '
    Server\DIR\OUT' too but same error. Do I have to add the NFS path of ECC into PI as logical path?
    Any suggestions?
    Thanks,
    Sangita

    Hello Sangita,
    Your ECC server is an external system, therefore you need to activate FTP service in that system and use the transport protocol FTP:
    http://help.sap.com/saphelp_nw04/helpdata/en/e3/94007075cae04f930cc4c034e411e1/content.htm
    You can use NFS protocol when you have a local directory in XI server.
    Best Regards,
    .Luis Bernal.

  • Reading file from oracle directory at client side

    Hi,
    I have a SWING app. which connects to an Oracle db.
    My goal is to read files from oracle directory with java through JDBC. I export some dumps with datapump and they need to be transferred to a client machine. There is no access to oracle directory at network filesystem level.
    Please advice!
    TIA, Sandor

    An Oracle Directory has an underlying OS directory associated with it, Oracle just overlays it's control structure onto an existing folder in the OS. You can manipulate the files with stored procedures in Oracle or at the OS level from outside of Oracle.
    If you manipulate the files from the OS level, outside of Oracle, you may need a refresh of the Oracle Directory structure.

  • A script to open files in a directory that have certain properties

    I need a script to open all JPG files in a directory and it's subfolders that have a height greater than the width and then run a specific photoshop action for each (inlcuding a save for web within the same directory). Not sure if it's best to record that into the action as it will probably always try to save in the same directory. Probably need something similar to the batch options available in Photoshop that override this...
    Any help is much appreciated.

    I think I found what I'm looking for in ImageReady although I'm not sure how to set it to batch. I don't see the batch command in the File menu like Photoshop...

  • Reading Files from client directory folder using servlets or struts.

    HI All,
    Could you please help me out int the below query.
    I want read all files from paricular directory folder from the client machine in web application. I am able to do it from my local machine. but when I am try to do it from some other machine I am not able to get the file list.
    It is very urgent ..please hep me ASAP.

    It should be problem with the file permissions in your client machine ???Hardly.
    @OP: a servlet executes at the server. It doesn't haved any access whatsoever to the client machine.

  • How to read files in whole directory

    hi everybosy i have got a directory called grepdatabase in the following path
    /users/zer/gd.
    it has 3000 files in it.i have to read each file and do soem process and write it into another file.
    but with the following code it says, directorydoesnot exists.but i have the directory,with all the files in it.
    File database = new File("c:/Domain/nbi.bbsrc.ac.uk/Users/zer/gd");
            if (database.exists() && database.isDirectory()) {
                String datafiles[] = database.list();
                for (int i = 0; i < datafiles.length; i++) {
                    System.out.println("processing file: " + database.getAbsolutePath() +
                            "/" + datafiles[0]);
            } else {
                System.out.println("Database exists: "+database.exists()+"\nDatabase is Directory: "+database.isDirectory());
            }can anyone help me how to read multiple files...

    ur code can be little modified as follows to make it work flawlessly
           File database = new File("c:/Domain/nbi.bbsrc.ac.uk/Users/zer/gd");
                  if (database.exists() && database.isDirectory()) {
                      //String datafiles[] = database.list();
                      //Instead use file list here
                      File[] datafiles = database.listFiles();
                      for (int i = 0; i < datafiles.length; i++) {
                      //    System.out.println("processing file: " + database.getAbsolutePath() +
                      //            "/" + datafiles[0]);
                       System.out.println("processing file: " + datafiles.getName());
    } else {
    System.out.println("Database exists: "+database.exists()+"\nDatabase is Directory: "+database.isDirectory());
    BR

  • How to read files from current directory for applet

    I have an applet that needs to read some audio files located in its current directory on the server and I just can't seem to figure it out...maybe I am being dumb...any help?

    You can use the ListSorter File Adapter Configuration property to sort based on timestamp. Basically add the following property to the inbound JCA file:
    <property name="ListSorter"
    value="oracle.tip.adapter.file.inbound.listing.TimestampSorterAscending"/>
    <property name="SingleThreadModel" value="true"/>
    More info see section 4.2.6 in http://docs.oracle.com/cd/E23943_01/integration.1111/e10231/adptr_file.htm

  • How cot create and read files in ALLUSERSPROFILE directory

    Hi,
    I have a program that is to be used both with Windows XP, Vista, 7 and 8. It should create and read a file in ALLUSERSPROFILE, which I have learned to be different directories in XP and the other Windows versions. But after looking all over internet, I can't
    find any clear answer how to do this. I thought the following should work, but it doesn't:
    testfile = fopen("%ALLUSERSPROFILE%/testfile.dat", "r");
    Although the file exist, testfile gets the value of zero. I've also tried other strings instead of "ALLUSERSPROFILE," but no luck. Could anyone tell me how to do this?
    Thanks in advance.

    I tried the following:
         SHGetKnownFolderPath( &FOLDERID_ProgramData, 0, 0, &userpath); 
    Then the program compiled. But it did not work:
         fopen("%userpath%\\Testfolder\\Testfile.ini", "r"); 
    did not open the file, although it is there.
    Then I read that this function can't be used with Windows XP, so I
    switched to the deprecated SHGetFolderPath 
        TCHAR userpath[MAX_PATH];
         SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, SHGFP_TYPE_CURRENT, userpath);
    According to the MSDN pages, one then could use the 
        PathAppend (userpath, TEXT("Testfolder/Testfile.ini"));
    I then added Shlwapi.h and compiled and got the following error message 
         main.obj : error LNK2001: unresolved external symbol __imp__PathAppendW@8  
         fatal error LNK1120: 1 unresolved externals
    Then I again tried 
       fopen("%userpath%\\Testfolder\\Testfile.ini", "r");
    but neither did this work. So now I don’t know what to do.

  • How can I read only text files in a directory.

    I've written a program to read files in a directory but I'd like for it to only read the text files of that directory.
    import java.io.*;
    public class Data {
      public static void main(String[] args) throws IOException {
      String target_dir = "C:\\files";
      File dir = new File(target_dir);
      File[] files = dir.listFiles();
      for (File textfiles : files) {
      if (textfiles.isFile()) {
      BufferedReader inputStream = null;
      try {
      inputStream = new BufferedReader(new FileReader(textfiles));
      String line;
      while ((line = inputStream.readLine()) != null) {
      System.out.println(line);
      } finally {
      if (inputStream != null) {
      inputStream.close();

    You have mentioned you want to read only text files.
    If you are referring to some specific set of extentions, you can filter based on that.
    ex: you want to read only .txt files, you can add an if condition as below :
              if(textfiles.getName().endsWith(".txt")) {
                  // Add your code here
    Cheers
    AJ

  • Reading file from AS with details

    Hi guys,
    I want to read files from a directory on AS.
    I used the FM SUBST_GET_FILE_LIST.
    It works fine, but I'd like to know the file creation date.
    I have to use this date time to decide which file I have to manage.
    I thought the MTIME field was the answer, but it returns to me a number that I don't understand.
    Any idea about it, or is there a FM that give to me the file creation date, modification date ecc
    Regards
    Jampierre

    From the description MTIME is the Unix time - "last modification date, seconds since 1970"; Meaning this number is time in seconds from 1970; Did you check out the MOD_DATE and MOD_TIME fields in the same output table?
    There are lot of threads in SDN regarding this and conversion of unix time to std date/time... please search in SDN,
    Convert UNIX timestamp into Date and Time
    Retrieve File creation date

  • FtpAdapter not reading files consistently

    I'm using Ftp Adapter to read files from ftps server. It is not reading files consistently. All of a sudden it stops reading the files. Once I restart the run time instance, it starts reading again. There are no errors in logs.
    The wsdl configurations and oc4j-ra.xml is given below. Is there any configurations to be done for clustered environment? There are 2 run time instances trying to read files from same directory in the same ftps server.
    WSDL
    <message name="Get_msg">
    <part name="opaque" element="opaque:opaqueElement" />
    </message>
    <portType name="Get_ptt">
    <operation name="Get">
    <input message="tns:Get_msg" />
    </operation>
    </portType>
    <binding name="Get_binding" type="tns:Get_ptt">
    <pc:inbound_binding />
    <operation name="Get">
    <jca:operation FileType="ascii" PhysicalDirectory="/users/PCGFTPS/test/inbound/272" ActivationSpec="oracle.tip.adapter.ftp.inbound.FTPActivationSpec" DeleteFile="true" IncludeFiles="saf272\.d.*\.t.*c.*" PollingFrequency="5" MinimumAge="0" OpaqueSchema="true" />
    <input>
    <jca:header message="hdr:InboundHeader_msg" part="inboundHeader" />
    </input>
    </operation>
    </binding>
    <service name="readFileFromFTPS">
    <port name="Get_pt" binding="tns:Get_binding">
    <jca:address location="eis/Ftp/edi/FtpAdapter" UIincludeWildcard="saf272.d*.t*c*" />
    </port>
    </service>
    <plt:partnerLinkType name="Get_plt">
    <plt:role name="Get_role">
    <plt:portType name="tns:Get_ptt" />
    </plt:role>
    </plt:partnerLinkType>
    </definitions>
    oc4j-ra.xml
    <config-property name="host" value="ftps.qa.com"/>
              <config-property name="port" value="21"/>
              <config-property name="username" value="ftps"/>
              <config-property name="password" value="8888"/>
              <config-property name="ftpAbsolutePathBegin" value="/"/>
              <config-property name="ftpPathSeparator" value="/"/>
              <config-property name="changeDirectory" value="false"/>
              <config-property name="enforceFileTypeFromSpec" value="false"/>
              <config-property name="keepConnections" value="true"/>
              <config-property name="keepAlive" value="false"/>
              <config-property name="serverType" value="win"/>
              <config-property name="serverLocaleLanguage" value=""/>
              <config-property name="serverLocaleCountry" value=""/>
              <config-property name="serverLocaleVariant" value=""/>
              <config-property name="serverEncoding" value=""/>
              <config-property name="defaultDateFormat" value="MMM d yyyy"/>
              <config-property name="recentDateFormat" value="MMM d HH:mm"/>
              <config-property name="serverTimeZone" value=""/>
              <config-property name="listParserKey" value="WIN"/>
              <config-property name="timeParserKey" value="default"/>
              <config-property name="useFtps" value="true"/>
              <config-property name="useImplicitSSL" value="false"/>
              <config-property name="walletLocation" value="/tools/da/oracle/swinstall/product/10.1.3.1/OAS11/opmn/conf/ssl.wlt/interfaces/ewallet.p12"/>
              <config-property name="walletPassword" value="oc4jadmin"/>
              <config-property name="channelMask" value="both"/>
              <config-property name="securePort" value="990"/>
              <config-property name="keyStoreProviderName" value="oracle.security.pki.OraclePKIProvider"/>
              <config-property name="keystoreType" value="PKCS12"/>
              <config-property name="keystoreAlgorithm" value="OracleX509"/>
              <config-property name="enableCipherSuits" value=""/>
              <config-property name="pkiProvider" value="OraclePKI"/>
              <config-property name="jsseProvider" value="OracleJSSE"/>
              <config-property name="proxyHost" value=""/>
              <config-property name="proxyPort" value=""/>
              <config-property name="proxyUsername" value=""/>
              <config-property name="proxyPassword" value=""/>
              <config-property name="proxyType" value=""/>
              <config-property name="proxyDefinitionFile" value=""/>
              <config-property name="useProxy" value="false"/>
              <config-property name="useSftp" value="false"/>
              <config-property name="authenticationType" value="password"/>
              <config-property name="preferredKeyExchangeAlgorithm" value="diffie-hellman-group1-sha1"/>
              <config-property name="preferredCompressionAlgorithm" value="none"/>
              <config-property name="preferredDataIntegrityAlgorithm" value="hmac-md5"/>
              <config-property name="preferredPKIAlgorithm" value="ssh-rsa"/>
              <config-property name="privateKeyFile" value=""/>
              <config-property name="preferredCipherSuite" value="blowfish-cbc"/>
              <config-property name="transportProvider" value="socket"/>
              <connection-pooling use="none">
              </connection-pooling>
              <security-config use="none">
              </security-config>

    The fact that two instances are reading the same directory doesn't look that good to me. In parallel, the DB Adapter, polling for new records must not have two instances polling for the same table! Another issue could be problems on the FTP server itself. FTP connections are in Passive mode. It could be that the FTP server runs into portnumbers that are blocked in the firewall. This can be read from FTP logging on the FTP server itself.

  • Read file gives java.lang.Nullpointer exception

    I am reading to read a ".txt" file created by "python code" and stored in my directory.
    If i comment the python code and store the file ("statusfile.txt') in the directory, the code is able to read the file. but when i uncomment and run the python code to generate the file ..it gives java.lang.NullPointerException.
    the two functions for reading the file and running the python code are separate but in the same class and are also called in one JSP. Does anyone have any suggestions.
    Someone did suggest me to use getResourceAsStream.. but i do not understand where to use it .. in the class (where i am doing the readfile function or where in the runpython function which basically generates the file) I did tried using it in JSP and also in the class.. but nothing seems to work. Also as i saw the examples.. getResourceAsStream is used for uploading properties or config files. I just want to simplying read the simpel text file which is already stored in the directory and return a boolean to JSP if reading file was a success.
    in short the algo is
    ON JSP:
    1) call class function to run python code
    2) call class function to read the generated in step 1.
    CLASS
    1) function runpython()
    // store generated files in the specified directory
    2) function readFile()
    //read file from specified directory
    //return boolean
    Any suggestions
    Thanx

    The problem is where is "your directory"?
    Creating a file by new File("myFile.txt") just puts it in the current working directory.
    Sometimes this is something like the bin directory.
    Most web applications use ServletContext.getRealPath("/")
    This turns a website relative reference into a file reference on the local machine.
    So you can say getRealPath("/index.html") and it will return the file (for example) C:\tomcat\webapps\root\index.html
    On to suggestions:
    Null pointer exception?
    Where is it coming from? Catch the exception and print a stack trace, to see if you can determine which line of code is causing it - which variable is null. Is it the actual file, or something you use to create the file?

  • Shell scripts to read data from a text file and to load it into a table

    Hi All,
    I have a text file consisting of rows and columns as follows,
    GEF001 000093625 MKL002510 000001 000000 000000 000000 000000 000000 000001
    GEF001 000093625 MKL003604 000001 000000 000000 000000 000000 000000 000001
    GEF001 000093625 MKL005675 000001 000000 000000 000000 000000 000000 000001 My requirement is that, i should read the first 3 columns of this file using a shell script and then i have to insert the data into a table consisting of 3 rows in oracle .
    the whole application is deployed in unix and that text file comes from mainframe. am working in the unix side of the application and i cant access the data directly from the mainframe. so am required to write a script which reads the data from text file which is placed in certain location and i have to load it to oracle database.
    so I can't use SQL * loader.
    Please help me something with this...
    Thanks in advance.

    1. Create a dictionary object in Oracle and assign it to the folder where your file resides
    2. Write a little procedure which opens the file in the newly created directory object using ULT_FILE and inside the FOR LOOP and do INSERTs to table you want
    3. Create a shell script and call that procedure
    You can use the post in my Blog for such issues
    [Using Oracle UTL_FILE, UTL_SMTP packages and Linux Shell Scripting and Cron utility together|http://kamranagayev.wordpress.com/2009/02/23/using-oracle-utl_file-utl_smtp-packages-and-linux-shell-scripting-and-cron-utility-together-2/]
    Kamran Agayev A. (10g OCP)
    http://kamranagayev.wordpress.com

  • Need a VB-Script that read a txt-file and only the lines that are new since last time

    Hi,
    I need help to write a VB script that read all new lines since the last time.
    For example:  The script reads the textfile at specific time, then 10 minutes later the script read the file again, and it should now only read the lines that are new since last time. Anyone that has such a script in your scriptingbox?
    cheers!
    DocHo
    Doc

    Based on the excellent idea by Pegasus, where is a VBScript solution. I use a separate file to save the last line count read from the file, then each time the file is read I update the line count. Only lines after the last count are output by the program:
    Option Explicit
    Dim strFile, objFSO, objFile, strCountFile, objCountFile, strLine, lngCount, lngLine
    Const ForReading = 1
    Const ForWriting = 2
    Const OpenAsASCII = 0
    Const CreateIfNotExist = True
    ' Specify input file to be read.
    strFile = "c:\Scripts\Example.log"
    ' Specify file with most recent line count.
    strCountFile = "c:\Scripts\Count.txt"
    ' Open the input file for reading.
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(strFile, ForReading)
    ' Check if the line count file exists.
    If (objFSO.FileExists(strCountFile) = False) Then
        ' Initial count is 0, so all lines are read.
        lngCount = 0
    Else
        ' Open the line count file.
        Set objCountFile = objFSO.OpenTextFile(strCountFile, ForReading)
        ' Read the most recent line count.
        Do Until objCountFile.AtEndOfStream
            lngCount = CLng(objCountFile.ReadLine)
        Loop
    End If
    ' Read the input file.
    lngLine = 0
    Do Until objFile.AtEndOfStream
        ' Count lines.
        lngLine = lngLine + 1
        strLine = objFile.ReadLine
        If (lngLine >= lngCount) Then
            ' Output the line.
            Wscript.Echo strLine
        End If
    Loop
    ' Close all files.
    objFile.Close
    If (lngCount > 0) Then
        objCountFile.Close
    End If
    ' Ignore last line of the file if it is blank.
    If (strLine = "") Then
        lngLine = lngLine - 1
    End If
    ' Save the new line count.
    Set objCountFile = objFSO.OpenTextFile(strCountFile, _
        ForWriting, CreateIfNotExist, OpenAsASCII)
    objCountFile.WriteLine CStr(lngLine + 1)
    objCountFile.Close
    Richard Mueller - MVP Directory Services

  • Script for moving files and directory to archive

    Hi,
    I've search the web for good working script to archive my files and folder with no luck.
    do you have a script that move and preserve the structure of older files and folders that have not been accessed for X days?

    Hello, I found this quite quickly in the TechNet Gallery. It seems like it would do what you're looking to do.
    https://gallery.technet.microsoft.com/Archive-old-files-with-042f859a
    # Powershell script - move old files to an archive location.
    # Writes log files to $logpath
    # Ver 0.6
    $path = "C:\TEMP"
    $archpath = "D:\TEMP-ARCH"
    $days = "30"
    $logpath = "C:\Temp"
    $date = Get-Date -format yyyyMMddHHmm
    write-progress -activity "Archiving Data" -status "Progress:"
    If ( -not (Test-Path $archpath)) {ni $archpath -type directory}
    Get-Childitem -Path $path -recurse| Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$days)} |
    ForEach { $filename = $_.fullname
    try { Move-Item $_.FullName -destination $archpath -force -ErrorAction:SilentlyContinue
    "Successfully moved $filename to $archpath" | add-content $logpath\log-$date.txt }
    catch { "Error moving $filename: $_ " | add-content $logpath\log-$date.txt }

Maybe you are looking for